<?php

namespace app\admin\model;

use think\Model;
use think\Db;
use think\db\exception\DbException;


class CategoryMoneyLog extends Model
{


    // 表名
    protected $name = 'category_money_log';

    public static function _do($category_id, $money, $type, $memo)
    {
        Db::startTrans();
        try {
            $before_money = Db::name('category')->where([
                'id' => $category_id,
            ])->value('balance');

            $rs1 = Db::name('category')->where([
                'id' => $category_id,
            ])->setInc('balance', $money);

            self::addLog($category_id, $type, $money, $before_money, $before_money + $money, $memo);

            Db::commit();
            return true;
        } catch (DbException $e) {
            Db::rollback();
            return false;
        }
    }

    //券金额
    public static function addLog($category_id, $type, $money, $before_money, $after_money, $memo)
    {
        $self = new self();
        $self->money_type = $type;
        $self->category_id = $category_id;
        $self->money = $money;
        $self->before_money = $before_money;
        $self->after_money = $after_money;
        $self->memo = $memo;
        $self->create_time = time();
        return $self->save();
    }
    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
